package com.cetcs.kmga.dataManager.util.socket;


import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.socket.WebSocketHandler;
import org.springframework.web.socket.server.support.HttpSessionHandshakeInterceptor;

import java.util.Map;

/**
 * @Description :创建握手（handshake）接口
 * Created by XingWen on 2016/12/23.
 */
@Component
public class HandshakeInterceptor extends HttpSessionHandshakeInterceptor {
    private static final Logger logger = LoggerFactory.getLogger(HandshakeInterceptor.class);

    @Override
    public boolean beforeHandshake(ServerHttpRequest request,
                                   ServerHttpResponse response, WebSocketHandler wsHandler,
                                   Map<String, Object> attributes) throws Exception {
        response.getHeaders().set("Access-Control-Allow-Origin", "*");
        System.out.println("After Handshake");
        logger.info("建立握手前...");
        ServletRequestAttributes attrs = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
//        ShiroUser currUser = ShiroOper.getSessionUser();
        //集成用户权限之后修改
        UserSocket userSocket = new UserSocket();
        userSocket.setUserId("0");
//        userSocket.setUserId(currUser!=null ? String.valueOf(currUser.getUserId()) : "");
        attributes.put("SESSION_USER", userSocket);

        return super.beforeHandshake(request, response, wsHandler, attributes);
    }

    @Override
    public void afterHandshake(ServerHttpRequest request,
                               ServerHttpResponse response, WebSocketHandler wsHandler,
                               Exception ex) {
        logger.info("建立握手后...");
        response.getHeaders().set("Access-Control-Allow-Origin", "*");
        System.out.println("After Handshake");
        super.afterHandshake(request, response, wsHandler, ex);
    }
}
